<?php

#<editor-fold defaultstate="collapsed" desc="CCore::Using">
CCore::Using('base.collection');
CCore::Using('base.datapointer');
CCore::Using('mime.header');
#</editor-fold>

class CCoreMimeMimePart
{
	#<editor-fold defaultstate="collapsed" desc="public">
	
	/**
	 * @var CCoreMimeHeadersCollection
	 */
	public $Headers;

	/**
	 * @var	CCoreMimeMimePartsCollection
	 */
	public $SubParts;

	#</editor-fold>
	#<editor-fold defaultstate="collapsed" desc="protected">
	/**
	 * @return	CCoreBaseDataPointer
	 */
	protected $oDataPointer;

	/**
	 * @return	CCoreBaseDataPointer
	 */
	protected $oBodyDataPointer;
	#</editor-fold>
	
	/**
	 * @param	CCoreBaseDataPointer	&$oDataPointer
	 * @return	CCoreMimeMimePart
	 */
	public function __construct(CCoreBaseDataPointer &$oDataPointer)
	{
		$this->Headers = null;
		$this->SubParts =  new CCoreMimeMimePartsCollection();

		$this->oDataPointer = $oDataPointer;
		$this->oBodyDataPointer = null;

		$this->_parse();
	}

	private function _parse()
	{
		$iPos = $this->oDataPointer->Search(array("\r\n\r\n", "\n\n"), 0);
		if (false !== $iPos)
		{
			$this->Headers = new CCoreMimeHeadersCollection(
				$this->oDataPointer->GetPartAsDataPointer(0, $iPos));

			$this->oBodyDataPointer = $this->oDataPointer->GetPartAsDataPointer($iPos);
			if ($this->oBodyDataPointer->Size() > 10)
			{
				$sBoundary = $this->Headers->GetBoundaryValue();
				$sBoundary = '--'.$sBoundary;
				$iBoundarySize = strlen($sBoundary);
				if (strlen($sBoundary) > 3)
				{
					$iStart = 0;
					
					while (true)
					{
						$iBoundaryPos = $this->oBodyDataPointer->Search($sBoundary, $iStart);
						if (false === $iBoundaryPos)
						{
							break;
						}

						if (null === $this->SubParts)
						{
							$this->SubParts = new CCoreMimeMimePartsCollection();
						}
						$this->SubParts->Add(new CCoreMimeMimePart(
							$this->oBodyDataPointer->GetPartAsDataPointer($iStart, $iBoundaryPos - $iStart)));

						$iStart += $iBoundaryPos - $iStart + $iBoundarySize;
					}
				}
			}
		}
	}
}

class CCoreMimeMimePartsCollection extends ACoreBaseCollection
{
	/**
	 * @return	CCoreMimeMimePartsCollection
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * @param	CCoreMimeMimePart	$oMimeHeader
	 * @return	void
	 */
	public function Add(CCoreMimeMimePart $oMimeHeader)
	{
		CCore::CheckTypes(array('$oMimeHeader'));

		parent::Add($oMimeHeader);
	}
}